import React from 'react'
import { observer, inject } from 'mobx-react'
import { observable } from 'mobx'

import Layout from '../Layout'

@inject('utils')
@observer
export default class BubbleUp extends React.Component {
  @observable data = []
  @observable contrast_idx = 0

  componentDidMount() {
    const { utils } = this.props

    this.data = utils.randomArray(50)
  }

  changeData(new_data) {
    this.data = new_data
  }

  async mathData(data, max) {
    const { utils } = this.props

    if (typeof max === 'undefined') {
      max = data.length - 1
    }

    let success = true
    for (let idx = 0; idx < max; idx++) {
      this.contrast_idx = idx
      if (data[idx + 1] < data[idx]) {
        ;[data[idx + 1], data[idx]] = [data[idx], data[idx + 1]]
        this.data = data
        success = false
      }
      await utils.sleep(1)
    }
    if (!success) {
      return this.mathData(data, --max)
    }
    return data
  }

  onStart() {
    this.mathData(this.data)
  }

  render() {
    return (
      <div>
        <div>冒泡排序（优化）</div>
        <Layout
          data={this.data.slice()}
          contrastIndex={this.contrast_idx}
          onStart={this.onStart.bind(this)}
        />
      </div>
    )
  }
}
